﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Carto;

namespace GISCommon.UI
{
    public partial class IdentityForm : Form
    {
        #region 变量
        private AxMapControl m_pMapControl;   //操作地图控件
        private ESRI.ArcGIS.SystemUI.ICommand  m_pTool;
        private bool m_IsForFind = false;
        private ESRI.ArcGIS.Geometry.IGeometry m_flashGeo = null;
        #endregion

        #region 公有函数

            #region 构造函数

        /// <summary>
        /// 描述：构造函数

        /// </summary>
        /// <param name="vMapControl"></param>
        public IdentityForm(AxMapControl vMapControl)
        {
            try
            {
                InitializeComponent();

                //设置地图控件
                m_pMapControl = vMapControl;

                //地图控件单击事件声明
                m_pMapControl.OnMouseUp += new ESRI.ArcGIS.Controls.IMapControlEvents2_Ax_OnMouseUpEventHandler(this.m_pMapControl_OnMouseUp);
                m_pMapControl.OnAfterScreenDraw += new IMapControlEvents2_Ax_OnAfterScreenDrawEventHandler(m_pMapControl_OnAfterScreenDraw);
                //设置选择工具功能
                m_pTool = (ESRI.ArcGIS.SystemUI.ICommand)new ESRI.ArcGIS.Controls.ControlsSelectFeaturesToolClass();
                m_pTool.OnCreate(m_pMapControl.Object);

                //lvw_Attribute.Columns["clh_FieldName"].Width = 0;
            }
            catch (Exception ex)
            {
                SysCommon.Global.mainLog.Error("调用IdentityForm(AxMapControl vMapControl)出错", ex);
            }
        }

        void m_pMapControl_OnAfterScreenDraw(object sender, IMapControlEvents2_OnAfterScreenDrawEvent e)
        {
            try
            {
                if (m_flashGeo != null)
                {
                    m_pMapControl.FlashShape(m_flashGeo);
                    m_flashGeo = null;
                }
            }
            catch (Exception ex)
            {
                SysCommon.Global.mainLog.Error("调用出错", ex);
            }
        }

        /// <summary>
        /// 描述：响应由Find调用的构造函数

        /// </summary>
        /// <param name="vFeature"></param>
        /// <param name="strLayerName"></param>
        public IdentityForm(IFeature vFeature, IFeatureLayer vFeatureLayer, AxMapControl vMapControl)
        {
            try
            {
                InitializeComponent();

                m_pMapControl = vMapControl;
                m_pMapControl.OnMouseUp += new IMapControlEvents2_Ax_OnMouseUpEventHandler(m_pMapControl_OnMouseUp);
                m_pMapControl.OnAfterScreenDraw+=new IMapControlEvents2_Ax_OnAfterScreenDrawEventHandler(m_pMapControl_OnAfterScreenDraw);
                //lbl_Tip.Visible = false;

                //向ListView填充vFeature的内容

                int intFieldCount = vFeature.Fields.FieldCount;
                for (int i = 0; i < intFieldCount; i++)
                {
                    ListViewItem ItmX = new ListViewItem();
                    int intNum = i + 1;
                    ItmX.Text = intNum.ToString();
                    ItmX.SubItems.Add(vFeature.get_Value(i).ToString());
                    ItmX.SubItems.Add(vFeature.Fields.get_Field(i).Name.ToString());

                    lvw_Attribute.Items.Add(ItmX);
                }

                //向TreeView填充vFeature的内容

                //tvw_Layers.CheckBoxes = true;
                tvw_Layers.Nodes.Add(vFeatureLayer.Name.ToString());
                string strDisplayField = vFeatureLayer.DisplayField.ToString();
                int index = vFeature.Fields.FindField(strDisplayField);
                string strDisplayName = (string)vFeature.get_Value(index);
                tvw_Layers.Nodes[0].Nodes.Add(vFeature.OID.ToString(), strDisplayName);
                tvw_Layers.ExpandAll();

                //设置选择工具功能
                m_pTool = (ESRI.ArcGIS.SystemUI.ICommand)new ESRI.ArcGIS.Controls.ControlsSelectFeaturesToolClass();
                m_pTool.OnCreate(m_pMapControl.Object);

                m_IsForFind = true;
            }
            catch (Exception ex)
            {
                SysCommon.Global.mainLog.Error("调用出错", ex);
            }

        }
            #endregion

            #region 显示窗体前发生

        /// <summary>
        /// 描述：显示窗体前发生
        /// </summary>
        public void BeforeShowForm()
        {
            try
            {
                if (!m_IsForFind)
                {
                    //清除ListView和TreeView的内容

                    this.lvw_Attribute.Items.Clear();
                    this.tvw_Layers.Nodes.Clear();
                }
                m_pMapControl.CurrentTool = (ESRI.ArcGIS.SystemUI.ITool)m_pTool;
            }
            catch (Exception ex)
            {
                SysCommon.Global.mainLog.Error("调用出错", ex);
            }
        }
            #endregion

        #endregion

        #region 私有函数

            #region 往ListView添加内容
        /// <summary>
        /// 描述：往ListView添加内容
        /// </summary>
        /// <param name="pFeature"></param>
        private void AddToListView(IFeature pFeature)
        {
            try
            {
                //向ListView填充vFeature的内容

                lvw_Attribute.Items.Clear();
                int intFieldCount = pFeature.Fields.FieldCount;
                for (int i = 0; i < intFieldCount; i++)
                {
                    ListViewItem ItmX = new ListViewItem();
                    int intNum = i + 1;
                    ItmX.Text = intNum.ToString();
                    ItmX.SubItems.Add(pFeature.get_Value(i).ToString());
                    //ItmX.SubItems.Add(pFeature.Fields.get_Field(i).Name.ToString());

                    lvw_Attribute.Items.Add(ItmX);
                }
            }
            catch (Exception ex)
            {
                SysCommon.Global.mainLog.Error("调用出错", ex);
            }

        }
            #endregion

            #region 往TreeView添加内容
        /// <summary>
        /// 描述：往TreeView添加内容
        /// </summary>
        /// <param name="pFeature"></param>
        private void AddToTreeView(IFeature pFeature,int index)
        {
            try
            {
                //向TreeView填充vFeature的内容

                IFeatureLayer pFeatureLayer = SearchFeatureLayer(pFeature);
                cmb_Layer.Text = pFeatureLayer.Name.ToString();

                tvw_Layers.Nodes.Add(pFeatureLayer.Name.ToString());
                string strDisplayField = pFeatureLayer.DisplayField.ToString();
                int indexField = pFeature.Fields.FindField(strDisplayField);
                string strDisplayName = (string)pFeature.get_Value(indexField);

                TreeNode treeNode = tvw_Layers.Nodes[index].Nodes.Add(pFeature.OID.ToString(), strDisplayName);
                //Console.WriteLine("树节点的名称：" + treeNode.Name.ToString());
                tvw_Layers.ExpandAll();
                //m_OID = pFeature.OID;
            }
            catch (Exception ex)
            {
                SysCommon.Global.mainLog.Error("调用出错", ex);
            }
        }
            #endregion

            #region 根据图层名称搜索图层
        /// <summary>
        /// 描述：根据图层名称搜索图层

        /// </summary>
        /// <param name="strLayerName">图层名</param>
        /// <returns></returns>
        private IFeatureLayer SearchFeatureLayer(string strLayerName)
        {
            try
            {
                int intCount = m_pMapControl.LayerCount;
                for (int i = 0; i < intCount; i++)
                {
                    IFeatureLayer pFeatureLayer = (IFeatureLayer)m_pMapControl.get_Layer(i);
                    if (pFeatureLayer.Name == strLayerName)
                    {
                        return pFeatureLayer;
                    }
                }
            }
            catch (Exception ex)
            {
                SysCommon.Global.mainLog.Error("调用出错", ex);
            }
            return null;
        }
            #endregion

            #region 根据图元搜索所在图层

        /// <summary>
        /// 描述：根据图元搜索所在图层

        /// </summary>
        /// <param name="vFeature">图元</param>
        /// <returns></returns>
        private IFeatureLayer SearchFeatureLayer(IFeature vFeature)
        {
            try
            {
                string strFeatureClassName = vFeature.Class.AliasName.ToString();
                int intCount = m_pMapControl.LayerCount;
                for (int i = 0; i < intCount; i++)
                {
                    IFeatureLayer pFeatureLayer = (IFeatureLayer)m_pMapControl.get_Layer(i);
                    IFeatureClass pFeatureClass = pFeatureLayer.FeatureClass;
                    string strFCName = pFeatureClass.AliasName.ToString();
                    if (strFeatureClassName == strFCName)
                    {
                        pFeatureClass = null;
                        return pFeatureLayer;
                    }
                }
            }
            catch (Exception ex)
            {
                SysCommon.Global.mainLog.Error("调用出错", ex);
            }
            return null;
        }
            #endregion

        #endregion

        #region 事件函数


            #region 响应地图控件的单击事件

        /// <summary>
        /// 描述：响应地图控件的单击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void m_pMapControl_OnMouseUp(object sender, IMapControlEvents2_OnMouseUpEvent e)
        {
            try
            {
                IEnumFeature pEnumFeature = (IEnumFeature)m_pMapControl.Map.FeatureSelection;
                IFeature pFeature;
                pFeature = pEnumFeature.Next();
                if (pFeature == null) return;

                //lbl_Tip.Visible = false;
                int counts = 0;
                tvw_Layers.Nodes.Clear();
                do
                {
                    AddToListView(pFeature);
                    AddToTreeView(pFeature, counts);
                    pFeature = pEnumFeature.Next();
                    counts++;
                } while (pFeature != null);
                m_pMapControl.Map.ClearSelection();
                m_pMapControl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeoSelection,
                    null, null);
            }
            catch (Exception ex)
            {
                SysCommon.Global.mainLog.Error("调用出错", ex);
            }
        }
            #endregion

            #region 响应TreeView单击事件
        /// <summary>
        /// 描述：响应TreeView单击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tvw_Layers_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            try
            {
                TreeNode CurrentNode = e.Node;
                TreeNode ChildNode;
                TreeNode ParentNode;
                //Console.WriteLine("CurrentNode's Name is " + CurrentNode.Text);
                int NodeCount = CurrentNode.Nodes.Count;
                //Console.WriteLine("CurrentNode's Node count is " +NodeCount);

                if (NodeCount > 0)
                {
                    ParentNode = CurrentNode;
                    ChildNode = CurrentNode.Nodes[0];
                }
                else
                {
                    ChildNode = CurrentNode;
                    ParentNode = CurrentNode.Parent;
                }

                string strLayerName = ParentNode.Text;
                IFeatureLayer pFeatureLayer = SearchFeatureLayer(strLayerName);

                if (pFeatureLayer != null)
                {
                    IQueryFilter pQueryFilter = (IQueryFilter)new QueryFilter();
                    IFeatureCursor pFeatureCursor;
                    IFeature pFeature;
                    pQueryFilter.WhereClause = "OBJECTID=" + ChildNode.Name;// m_OID;
                    pFeatureCursor = pFeatureLayer.Search(pQueryFilter, false);
                    pFeature = pFeatureCursor.NextFeature();

                    if (pFeature != null)
                    {
                        ESRI.ArcGIS.Geometry.IGeometry pShape = pFeature.Shape;
                        //ESRI.ArcGIS.Geometry.esriGeometryType gtm = ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryMultipoint;
                        switch (pShape.GeometryType)
                        {
                            case ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryMultipoint:
                                ESRI.ArcGIS.Geometry.IMultipoint pMP = (ESRI.ArcGIS.Geometry.IMultipoint)pShape;
                                ESRI.ArcGIS.Geometry.IPointCollection pPC = (ESRI.ArcGIS.Geometry.IPointCollection)pMP;
                                ESRI.ArcGIS.Geometry.IPoint pPT = pPC.get_Point(0);
                                ESRI.ArcGIS.Geometry.ITopologicalOperator pTO = (ESRI.ArcGIS.Geometry.ITopologicalOperator)pPT;

                                pShape = pTO.Buffer(0.00001);
                                break;
                            case ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPoint:
                                //ESRI.ArcGIS.Geometry.ITopologicalOperator pTO = (ESRI.ArcGIS.Geometry.ITopologicalOperator)pShape;
                                pTO = (ESRI.ArcGIS.Geometry.ITopologicalOperator)pShape;
                                pShape = pTO.Buffer(0.0001);
                                break;
                            case ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPolyline:
                                pTO = (ESRI.ArcGIS.Geometry.ITopologicalOperator)pShape;
                                pShape = pTO.Buffer(0.0005);
                                break;
                        }

                        m_pMapControl.ActiveView.ScreenDisplay.DisplayTransformation.Bounds =
                            pShape.Envelope;
                        m_pMapControl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography,
                            null, null);
                        m_flashGeo = pShape;
                        //m_pMapControl.FlashShape(pShape);
                    }

                    AddToListView(pFeature);
                }

            }
            catch (Exception ex)
            {
                SysCommon.Global.mainLog.Error("调用出错", ex);
            }
        }
            #endregion

            #region 关闭按钮
        private void frm_Identity_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                m_pMapControl.Map.ClearSelection();
                m_pMapControl.CurrentTool = null;
                m_pMapControl.MousePointer = esriControlsMousePointer.esriPointerDefault;
                m_pMapControl.Refresh();
                this.Hide();
                e.Cancel = true;
            }
            catch (Exception ex)
            {
                SysCommon.Global.mainLog.Error("调用出错", ex);
            }
        }
            #endregion

        #endregion
    }
}